package cn.candy.basic.service.impl;

import cn.candy.basic.mapper.BaseMapper;
import cn.candy.basic.query.BaseQuery;
import cn.candy.basic.service.IBaseService;
import cn.candy.basic.util.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

//@Service //创建对象的 - 有泛型如何创建对象？ - 在具体使用的时候再创建
//疑问1：在使用时，继承之后会不会出问题
//在父类添加事务控制
//疑问2：在子类使用时，子类的方法会不会有事务控制

/**
 * Service实现基类
 * @param <T> 泛型
 */
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class BaseServiceImpl<T> implements IBaseService<T> {

    @Autowired
    private BaseMapper<T> baseMapper;

    @Override
    @Transactional
    public void add(T t) {
        baseMapper.save(t);
    }

    @Override
    @Transactional
    public void del(Long id) {
        baseMapper.remove(id);
    }

    @Override
    @Transactional
    public void update(T t) {
        baseMapper.update(t);
    }

    @Override
    public T findOne(Long id) {
        return baseMapper.loadById(id);
    }

    @Override
    public List<T> findAll() {
        return baseMapper.loadAll();
    }

    @Override
    public PageList<T> queryPage(BaseQuery baseQuery) {
        //先查询总数量
        Long totals = baseMapper.queryCount(baseQuery);
        if(totals == null || totals < 1 ){//没有数据的时候提高查询效率
            return new PageList<>();
        }
        //查询当前页的数据
        List<T> data = baseMapper.queryData(baseQuery);

        return new PageList<>(totals,data);
    }

    @Override
    public void batchRemove(List<Long> ids) {
        baseMapper.batchRemove(ids);
    }
}
